//
//  OnliePkResultVC.swift
//  MM2
//
//  Created by 李成明 on 2022/1/13.
//


import UIKit

private class SelfView: UIView {
    
    static let viewHeight: CGFloat = 560
    override init(frame: CGRect) {
        super.init(frame: frame)
        clipsToBounds = true
//        backgroundColor = .white
        layer.masksToBounds = true
        layer.cornerRadius = 10
        layer.borderWidth = 1
        layer.borderColor = UIColor.initWithRGB(87, 250, 255).cgColor
        
        addSubview(imgView)
        addSubview(faceValueLabel)
        imgView.snp.makeConstraints { make in
            make.right.top.equalTo(self)
            make.left.equalTo(self).offset(16)
            make.height.equalTo(imgView.snp.width)
        }
        
        faceValueLabel.snp.makeConstraints { make in
            make.bottom.equalTo(self).offset(-10)
            make.centerX.equalTo(self)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var faceValue: Float = 0 {
        didSet {
            faceValueLabel.text = "\(faceValue)"
        }
    }
    
    var image: UIImage? {
        didSet {
            imgView.image = image
        }
    }
    private var currentSubY: CGFloat = kScreenWidth/2
    
    lazy var imgView: UIImageView = {
        let view = UIImageView()
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 10
        view.contentMode = .scaleAspectFit
        return view
    }()
    
    private lazy var faceValueLabel: UILabel = {
        let view = UILabel()
        view.font = UIFont(name: faceValueFontStr, size: 30)
        view.textColor = faceValueColor
        return view
    }()
    
    func setBarrageViewShowFrame(barrageView: SingleAnalyzeBarrageView) {
        let startFrame = CGRect(x: -barrageView.viewWidth, y: currentSubY, width: barrageView.viewWidth, height: barrageView.viewHeight)
        let endFrame = CGRect(x: 16, y: currentSubY, width: barrageView.viewWidth, height: barrageView.viewHeight)
        barrageView.startAnimation(duration: 1, startFrame: startFrame, endFrame: endFrame)
        currentSubY += (barrageView.viewHeight + 10)
    }
}

private class PkView: UIView {
    static let viewHeight: CGFloat = 560
    override init(frame: CGRect) {
        super.init(frame: frame)
        clipsToBounds = true
//        backgroundColor = .white
        layer.masksToBounds = true
        layer.cornerRadius = 10
        layer.borderWidth = 1
        layer.borderColor = UIColor.initWithRGB(87, 250, 255).cgColor
        
        addSubview(imgView)
        addSubview(faceValueLabel)
        imgView.snp.makeConstraints { make in
            make.left.top.equalTo(self)
            make.right.equalTo(self).offset(-16)
            make.height.equalTo(imgView.snp.width)
        }
        
        faceValueLabel.snp.makeConstraints { make in
            make.bottom.equalTo(self).offset(-10)
            make.centerX.equalTo(self)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    var faceValue: Float = 0 {
        didSet {
            faceValueLabel.text = "\(faceValue)"
        }
    }
    
    var imgStr: String? {
        didSet {
            imgView.setImageWithUrlStr(imgStr)
        }
    }
    private var currentSubY: CGFloat = kScreenWidth/2
    
    private lazy var imgView: UIImageView = {
        let view = UIImageView()
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 10
        view.contentMode = .scaleAspectFit
        return view
    }()
    
    private lazy var faceValueLabel: UILabel = {
        let view = UILabel()
        view.font = UIFont(name: faceValueFontStr, size: 30)
        view.textColor = faceValueColor
        return view
    }()
    
    func setBarrageViewShowFrame(barrageView: SingleAnalyzeBarrageView) {
        let startFrame = CGRect(x: kScreenWidth/2, y: currentSubY, width: barrageView.viewWidth, height: barrageView.viewHeight)
        let endFrame = CGRect(x: kScreenWidth/2 - barrageView.viewWidth - 16, y: currentSubY, width: barrageView.viewWidth, height: barrageView.viewHeight)
        barrageView.startAnimation(duration: 1, startFrame: startFrame, endFrame: endFrame)
        currentSubY += (barrageView.viewHeight + 10)
    }
}
class OnliePkResultVC: MViewController {
    
    init(selfModel: RankListModel, pkUserModel: RankListModel) {
        self.selfResultModel = selfModel
        self.pkUserModel = pkUserModel
        super.init(nibName: nil, bundle: nil)
        
        self.selfView.imgView.setImageWithUrlStr(selfModel.imgUrl)
        self.pkView.imgStr = pkUserModel.imgUrl
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        startAnmation()
    }

    var pkUserModel: RankListModel
    
    private var selfResultModel: RankListModel
    
    private lazy var navBar: MNavBar = {
        let view = MNavBar(frame: CGRect(x: 0, y: kStateBarHeight, width: kScreenWidth, height: kNaviBarHeight))
        view.back { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }.title = "PK结果"
        return view
    }()

    private lazy var selfView: SelfView = {
        let view = SelfView.init(frame: CGRect(x: 0, y: kStateAndNavH + 20, width: kScreenWidth/2, height: SelfView.viewHeight))
        return view
    }()

    private lazy var pkView: PkView = {
        let view = PkView.init(frame: CGRect(x: kScreenWidth/2, y: kStateAndNavH + 20, width: kScreenWidth/2, height: PkView.viewHeight))
        return view
    }()
    
    private lazy var bgView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "face_anly_bg_img"))
        return view
    }()
    
    private lazy var pkResultImg: UIImageView = {
        let view = UIImageView()
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 10
        return view
    }()
    
    private lazy var pkResultLabel: UILabel = {
        let view = UILabel()
        view.font = .systemFont(ofSize: 16)
        view.textColor = faceValueColor
        view.isHidden = true
        view.numberOfLines = 0
        view.text = "哦，该死，你的容颜应该申请吉尼斯纪录！"
        view.textAlignment = .center
        return view
    }()
    
    private var animationArea = (begin: kStateAndNavH + 20, height: kScreenWidth/2 - 16)
    private var showArea = (begin: kStateAndNavH + 20 + kScreenWidth/2 - 16, height: 200)
    private var selfViewArr: [(SingleAnalyzeBarrageView, CGFloat)] = []
    private var rankViewArr: [(SingleAnalyzeBarrageView, CGFloat)] = []
}

extension OnliePkResultVC {
    private func setupUI() {
        view.addsubViews([bgView, navBar, selfView, pkView, pkResultImg, pkResultLabel])
        bgView.frame = view.bounds
        
        pkResultImg.snp.makeConstraints { make in
            make.top.equalTo(selfView.snp.bottom).offset(8)
            make.centerX.equalTo(view)
            make.size.equalTo(CGSize(width: 80, height: 80))
        }
        
        pkResultLabel.snp.makeConstraints { make in
            make.top.equalTo(pkResultImg.snp.bottom)
            make.left.bottom.right.equalTo(view)
        }
    }
    
    private func startAnmation() {
//        guard let selfResultModel = selfResultModel, let pkUserModel = pkUserModel else { return }
        let itemH = SingleAnalyzeBarrageView.staticViewHeight
        let spaceH = (animationArea.height - itemH*3)/2
        
        var y = 0.0
        for item in selfResultModel.getValueArray() {
            let itemView = SingleAnalyzeBarrageView.init(frame: CGRect(x: 0, y: -50, width: 0, height: 0), isLeft: true)
            itemView.faceAnalyzeType = item
            selfViewArr.append((itemView, y))
            selfView.addSubview(itemView)
            
            y =  ((y + itemH + spaceH) > animationArea.height) ? 0 : (y + itemH + spaceH)
        }
        
        y = 0
        for item in pkUserModel.getValueArray() {
            let itemView = SingleAnalyzeBarrageView.init(frame: CGRect(x: 0, y: -50, width: 0, height: 0), isLeft: false)
            itemView.faceAnalyzeType = item
            rankViewArr.append((itemView, y))
            pkView.addSubview(itemView)
            
            y =  ((y + itemH + spaceH) > animationArea.height) ? 0 : (y + itemH + spaceH)
        }
        
        Util.dispatchTimer(timeInterval: 0.25, repeatCount: selfViewArr.count) { _, count in
            let item = self.selfViewArr[count]
            if count == 0 {
                self.doAnimation(item, isLeft: true) { [weak self] in
                    self?.selfView.faceValue = self?.selfResultModel.faceValue ?? 0
                    self?.setPkResult()
                }
            } else {
                self.doAnimation(item, isLeft: true)
            }
        }
        
        Util.dispatchTimer(timeInterval: 0.25, repeatCount: rankViewArr.count) { _, count in
            let item = self.rankViewArr[count]
            if count == 0{
                self.doAnimation(item, isLeft: true) { [weak self] in
                    self?.pkView.faceValue = self?.pkUserModel.faceValue ?? 0
                }
            } else {
                self.doAnimation(item, isLeft: false)
            }
        }
    }
    
    private func setPkResult() {
        let isWin = selfResultModel.faceValue >= pkUserModel.faceValue
        pkResultImg.image = isWin ? UIImage(named: "pk_winner") : UIImage(named: "pk_lost")
        pkResultLabel.isHidden = !isWin
        
        let lostH = kScreenHeight - kStateAndNavH - 28 - SelfView.viewHeight - kSafeAreaBottomH
        let imgSize = isWin ? CGSize(width: 50, height: 50) : CGSize(width: lostH, height: lostH)
        pkResultImg.snp.updateConstraints { make in
            make.size.equalTo(imgSize)
        }
        
        if let image = Util.rendImageWithView(self.view) {
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
        }
    }
    
    private func doAnimation(_ item: (SingleAnalyzeBarrageView, CGFloat), isLeft: Bool, completion: (() -> Void)? = nil) {
        let view = item.0
        let frameY = item.1
        let startFrame = isLeft ? CGRect(x: -view.viewWidth, y: frameY, width: view.viewWidth, height: view.viewHeight) : CGRect(x: kScreenWidth/2, y: frameY, width: view.viewWidth, height: view.viewHeight)
        let endFrame = isLeft ? CGRect(x: kScreenWidth/2, y: frameY, width: view.viewWidth, height: view.viewHeight) : CGRect(x: -view.viewWidth, y: frameY, width: view.viewWidth, height: view.viewHeight)
        view.startAnimation(duration: 1.5, startFrame: startFrame, endFrame: endFrame) { barrView in
            (barrView.superview as? SelfView)?.setBarrageViewShowFrame(barrageView: barrView)
            (barrView.superview as? PkView)?.setBarrageViewShowFrame(barrageView: barrView)
            completion?()
        }
    }
}

